package com.geekcoding.geekoj.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.geekcoding.geekoj.entity.Question;
import com.geekcoding.geekoj.entity.Test;
import com.geekcoding.geekoj.entity.TestAnswer;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.mapper.TestAnswerMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Repository
public class TestAnswerRepository extends BaseRepository<TestAnswer, TestAnswer, TestAnswerMapper>{

    @Override
    public TestAnswer convert(TestAnswer entity) {
        return entity;
    }

    public TestAnswer nullOrCreate(Test test, Question question, UserEntity userEntity) {
        LambdaQueryWrapper<TestAnswer> wrapper = Wrappers.<TestAnswer>lambdaQuery().eq(TestAnswer::getTestId, test.getId()).eq(TestAnswer::getQuestionId,
                question.getId()).eq(TestAnswer::getAnswerId, userEntity.getId());
        TestAnswer testAnswer = baseMapper.selectOne(wrapper);
        if(Objects.isNull(testAnswer)){
            testAnswer = TestAnswer.builder()
                    .testId(test.getId())
                    .answerId(userEntity.getId())
                    .questionId(question.getId())
                    .build();
        }
        return testAnswer;
    }

    public TestAnswer query(Test test, Question question){
        LambdaQueryWrapper<TestAnswer> wrapper = Wrappers.<TestAnswer>lambdaQuery()
                .eq(TestAnswer::getTestId, test.getId())
                .eq(TestAnswer::getQuestionId, question.getId())
                .eq(TestAnswer::getAnswerId, test.getAnswerId());
        return baseMapper.selectOne(wrapper);
    }

    public List<Map<String, Object>> rankingByCount() {
        return baseMapper.rankingByCount();
    }

    public List<Map<String, Object>> rankingByYes() {
        return baseMapper.rankingByYes();
    }

    public List<Map<String, Object>> rankingByNo() {
        return baseMapper.rankingByNo();
    }
}
